package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author : [wangtao]
 * @className : DishController
 * @description : []
 * @createTime : [2022/10/10 13:01]
 * @updateTime : [2022/10/10 13:01]
 */
@RestController

@Slf4j
@RequestMapping("/common")

public class CommonController {

    @Value("${reggie.path}")
    private String basepath;
//private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
//        log.info("basepath= {}", basepath);
        String originalfilename = file.getOriginalFilename();
        String suffix = originalfilename.substring(originalfilename.lastIndexOf("."));
        String str = UUID.randomUUID().toString() + suffix;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String format = sdf.format(new Date());
        String savepath = format + "/" + str;
        File dir = new File(basepath + format);
        dir.mkdirs();

        try {
            file.transferTo(new File(dir + "/" + str));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(savepath);
    }

    @GetMapping("/download")
    public void downlown(HttpServletResponse response, String name) {
//        log.info("response:{},fileName:{}", response, name);
        try {
            FileInputStream is = new FileInputStream(basepath + "/" + name);
            ServletOutputStream outputStream = response.getOutputStream();
            byte by[] = new byte[1024];
            int index;
            while ((index = is.read(by)) != -1) {
                outputStream.write(by, 0, index);
            }
            outputStream.flush();
            outputStream.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
